library(tidySEM)
library(lavaan)
library(ggplot2)

source("~/Dropbox/Projects/Acquiescence Bias/Study 4/Drew/study4_recoding.R")

# basic model to then edit for visual
mod <- '
# substantive
pop =~ pop_fewints
+ pop_crooked
+ pop_nomethink
+ pop_polsimprove
+ pop_yesmethink
+ pop_benefitall

rr =~ rr_specfavr
+ rr_thard
+ rr_pdisc
+ rr_dless

# method
method =~ pop_fewints
+ 1*pop_crooked
+ 1*pop_nomethink
+ 1*pop_polsimprove 
+ 1*pop_yesmethink
+ 1*pop_benefitall
+ 1*rr_specfavr
+ 1*rr_thard
+ 1*rr_pdisc
+ 1*rr_dless

# covariances
method ~~ 0*pop + 0*rr
'

out <- sem(mod, bov)

# prepare data for graph
p_data <- prepare_graph(out, 
                        layout = get_layout("", "", "", "pop", "", "", "", "rr", "", "",
                                            "pop_fewints", "pop_crooked", "pop_nomethink", "pop_polsimprove", "pop_yesmethink", "pop_benefitall", "rr_specfavr", "rr_thard", "rr_pdisc", "rr_dless",
                                            "", "", "", "", "", "method", "", "", "", "",
                                            rows = 3),
                        ellipses_width = 3,
                        rect_height = .5)

# Set original labels to blank
p_data$nodes$label <- "" 
p_data$nodes$x[which(p_data$nodes$name == "method")] <- 11
p_data$nodes$x[which(p_data$nodes$name == "pop")] <- 7
p_data$nodes$x[which(p_data$nodes$name == "rr")] <- 17

nodes_df <- p_data$nodes
nodes_df$label <- c("Acquiescence", 
                    "Populism",
                    "Pop6",
                    "Pop2",
                    "Pop1",
                    "Pop3",
                    "Pop4",
                    "Pop5",
                    "Racial~Resentment",# ~ functions as whitespace for parsing
                    "RR4",
                    "RR3",
                    "RR1",
                    "RR2"
)

# modify edges
# Math Notation in Graphs https://cran.r-project.org/web/packages/tidySEM/vignettes/Plotting_graphs.html from Lambda
edges(p_data)$label[1:10] <- ""
edges(p_data)$label[c(1,7)] <- "1.00"
edges(p_data)$show[21:35] <- FALSE
edges(p_data)$label[36] <- ""
edges(p_data)$connect_from[which(edges(p_data)$from == "pop")] <- "bottom"
edges(p_data)$connect_from[which(edges(p_data)$from == "rr")] <- "bottom"
edges(p_data)$connect_from[which(edges(p_data)$from == "method")] <- "top"
edges(p_data)$connect_to[which(edges(p_data)$from == "pop")] <- "top"
edges(p_data)$connect_to[which(edges(p_data)$from == "rr")] <- "top"
edges(p_data)$connect_to[which(edges(p_data)$from == "method")] <- "bottom"
edges(p_data)$connect_to[36] <- "bottom"
edges(p_data)$label_color <- "white"
edges(p_data)$label_fill <- "black"

# plot
plot(p_data) + geom_text(data = nodes_df, aes(x=x, y=y, label=label), parse = TRUE)
ggsave("figure4.pdf", width = 10, height = 6)
